import os
import glob
from pathlib import Path
from typing import Dict, List, Optional

def read_all_txt_files(data_dir: str = "data") -> Dict[str, str]:
    """
    从指定目录读取所有 txt 文件的内容
    
    Args:
        data_dir (str): 数据目录路径，默认为 "data"
        
    Returns:
        Dict[str, str]: 字典，键为文件名，值为文件内容
    """
    txt_files_content = {}
    
    try:
        # 获取数据目录的绝对路径
        data_path = Path(data_dir)
        
        if not data_path.exists():
            print(f"错误：目录 '{data_dir}' 不存在")
            return txt_files_content
        
        if not data_path.is_dir():
            print(f"错误：'{data_dir}' 不是一个目录")
            return txt_files_content
        
        # 查找所有 txt 文件
        txt_files = list(data_path.glob("*.txt"))
        
        if not txt_files:
            print(f"在目录 '{data_dir}' 中没有找到任何 txt 文件")
            return txt_files_content
        
        print(f"在目录 '{data_dir}' 中找到 {len(txt_files)} 个 txt 文件:")
        
        # 读取每个 txt 文件的内容
        for txt_file in txt_files:
            try:
                with open(txt_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    txt_files_content[txt_file.name] = content
                    print(f"  ✓ 成功读取: {txt_file.name} ({len(content)} 字符)")
            except UnicodeDecodeError:
                # 如果 UTF-8 解码失败，尝试其他编码
                try:
                    with open(txt_file, 'r', encoding='gbk') as f:
                        content = f.read()
                        txt_files_content[txt_file.name] = content
                        print(f"  ✓ 成功读取 (GBK编码): {txt_file.name} ({len(content)} 字符)")
                except Exception as e:
                    print(f"  ✗ 读取文件失败: {txt_file.name} - {e}")
            except Exception as e:
                print(f"  ✗ 读取文件失败: {txt_file.name} - {e}")
        
        return txt_files_content
        
    except Exception as e:
        print(f"读取目录时出错: {e}")
        return txt_files_content

def read_specific_txt_file(file_path: str) -> Optional[str]:
    """
    读取指定的 txt 文件内容
    
    Args:
        file_path (str): 文件路径
        
    Returns:
        Optional[str]: 文件内容，读取失败时返回 None
    """
    try:
        file_path = Path(file_path)
        if not file_path.exists():
            print(f"错误：文件 '{file_path}' 不存在")
            return None
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"成功读取文件: {file_path.name} ({len(content)} 字符)")
            return content
            
    except UnicodeDecodeError:
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                content = f.read()
                print(f"成功读取文件 (GBK编码): {file_path.name} ({len(content)} 字符)")
                return content
        except Exception as e:
            print(f"读取文件失败: {e}")
            return None
    except Exception as e:
        print(f"读取文件失败: {e}")
        return None

def get_txt_files_list(data_dir: str = "data") -> List[str]:
    """
    获取指定目录中所有 txt 文件的列表
    
    Args:
        data_dir (str): 数据目录路径，默认为 "data"
        
    Returns:
        List[str]: txt 文件名列表
    """
    try:
        data_path = Path(data_dir)
        if not data_path.exists():
            print(f"错误：目录 '{data_dir}' 不存在")
            return []
        
        txt_files = [f.name for f in data_path.glob("*.txt")]
        return txt_files
        
    except Exception as e:
        print(f"获取文件列表时出错: {e}")
        return []

def main():
    """测试函数"""
    print("=" * 60)
    print("📁 读取 data 目录中的所有 txt 文件")
    print("=" * 60)
    
    # 读取所有 txt 文件
    all_content = read_all_txt_files()
    
    if all_content:
        print(f"\n📊 总共读取了 {len(all_content)} 个文件:")
        print("-" * 40)
        
        for filename, content in all_content.items():
            print(f"\n📄 文件: {filename}")
            print(f"📏 长度: {len(content)} 字符")
            print(f"📝 内容预览:")
            # 显示前200个字符作为预览
            preview = content[:200].replace('\n', '\\n')
            if len(content) > 200:
                preview += "..."
            print(f"   {preview}")
    else:
        print("没有读取到任何文件内容")

if __name__ == "__main__":
    main() 